const http = require("http");
const server = http.createServer(function (req, res) {
  let data = "";
  req.on("data", function (chunk) {
    data += chunk;
  });
  req.on("end", function () {
    let method = req.method;
    let utl = req.url;
    let headers = JSON.stringify(req.headers);
    let httpVersion = req.httpVersion;
    res.writeHead(200, {
      "Content-Type": "text/html;charset=utf-8",
    });
    let dataHtml = "<p>data: " + data + "</p>";
    let methosHtml = "<p>method: " + method + "</p>";
    let urlHtml = "<p>url: " + utl + "</p>";
    let headersHtml = "<p>headers: " + headers + "</p>";
    let httpVersionHtml = "<p>httpVersion: " + httpVersion + "</p>";
    let resData =
      dataHtml + methosHtml + urlHtml + headersHtml + httpVersionHtml;
    res.end(resData);
  });
});

server.listen(3000, function () {
  console.log("server is running at http://127.0.0.1:3000");
});

/**
 * http.IncomingMessage是http请求的信息，提供了以下3个事件
 * data：当请求的数据到达时触发
 * end：当请求的数据全部到达时触发
 * close：当请求被关闭时触发
 * 
 * http.ServerResponse是http响应的信息，提供了以下3个方法
 * respond.writeHead()：设置响应头
 * respond.write()：向客户端写入数据
 * respond.end()：结束响应
 * 
 */